package com.xzd.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(value="/test")
public class MyTest {

	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView(){
		return new ModelAndView();
	}
	
	@RequestMapping(value="/init")
	public ModelAndView saveU() throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("test");
		return mv;
	}
	
	@RequestMapping(value="/init1")
	public String init1(Model model) throws Exception{
		model.addAttribute("test", 112);
		return "testvm";
	}
	
	@RequiresPermissions("/aa/bb")
	@RequestMapping(value="/init2")
	public String init2(){
		return "init2";
	}
	
	@RequestMapping(value="/index2")
	public String unlogin() throws Exception{
		return "login";
	}
	
	@RequestMapping(value="/login")
	public String login(Model model) throws Exception{
		return "login";
	}
	
	@ResponseBody
	@RequestMapping(value="/login_check")
	public Map<String,Object> initVm(
			@RequestParam(required = false, value = "loginName", defaultValue = "") String loginName,
			@RequestParam(required = false, value = "password", defaultValue = "") String password) throws Exception{
		//model.addAttribute("test", "xzd");
		Map<String,Object> map = new HashMap<String,Object>();
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginName, password.toCharArray(),true);
		
		try {
			System.out.println(subject);
			if(!subject.isAuthenticated()){
				subject.login(token);
			}
			
			map.put("result","success");
		} catch (UnknownAccountException e) {
			//e.printStackTrace();
			System.out.println("user...");
			map.put("result","usererror");
		}catch (AuthenticationException e) {
			//e.printStackTrace();
			System.out.println("name...");
			map.put("result","usererror");
		}
		
		return map;
	}
	
	@RequestMapping(value="/loginOut")
	public String login() throws Exception{
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
	
}
